# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def longestUnivaluePath(self, root: TreeNode) -> int:
        def func(node, ans):
            if node is None:
                return 0
            leftVal = func(node.left, ans)
            rightVal = func(node.right, ans)
            leftVal = leftVal + 1 if node.left and node.left.val == node.val else 0
            rightVal = rightVal + 1 if node.right and node.right.val == node.val else 0
            ans[0] = max(ans[0], leftVal + rightVal)
            return max(leftVal, rightVal)

        ans = [0]
        func(root, ans)

        return ans[0]
